<template>
  <el-container class="attendance-container" v-loading="loading">
    <!-- 顶部筛选区域 -->
    <el-header class="header">
      <div class="header-left">
        <span class="label">选择月份：</span>
        <el-date-picker v-model="selectedMonth" type="month" placeholder="请选择" format="YYYY-MM" value-format="YYYY-MM"
          @change="handleMonthChange" />
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleExport">导出</el-button>
      </div>
    </el-header>

    <!-- 表格标题 -->
    <div class="table-header">
      <div class="title-wrapper">
        <el-icon class="title-icon">
          <List />
        </el-icon>
        <span class="title-text">考勤统计表</span>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-main class="container bc-table">
      <el-table :data="tableData" style="width: 100%; height: 100%">
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="成员姓名" align="center" />
        <el-table-column prop="requiredDays" label="应出勤(天)" align="center" />
        <el-table-column prop="actualDays" label="实际出勤(天)" align="center" />
        <el-table-column prop="morningShifts" label="上午班(次)" align="center" />
        <el-table-column prop="afternoonShifts" label="下午班(次)" align="center" />
        <el-table-column prop="abnormalCount" label="异常/缺勤(次)" align="center" />
        <el-table-column prop="attendanceRate" label="出勤率(%)" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <span :class="getStatusClass(scope.row.status)">
              {{ scope.row.status }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleViewDetail(scope.row)">
              查看明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <!-- 分页区域 -->
    <el-footer class="footer mt20">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50, 100]"
        :total="total" layout="total,sizes, prev, pager, next, jumper" :background="true"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页" />
    </el-footer>
  </el-container>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { List } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const router = useRouter();

// 加载状态
const loading = ref(false);

// 选中的月份
const selectedMonth = ref("");

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(400);

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value);
});

// 表格数据
const tableData = ref([]);

// 生成模拟数据
const generateMockData = () => {
  const names = ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"];
  const data = [];

  for (let i = 0; i < 400; i++) {
    const name = names[i % names.length];
    const requiredDays = 30;
    const actualDays = Math.floor(Math.random() * 31);
    const morningShifts = actualDays > 0 ? Math.max(0, actualDays - Math.floor(Math.random() * 3)) : 0;
    const afternoonShifts = actualDays > 0 ? Math.max(0, actualDays - Math.floor(Math.random() * 3)) : 0;
    const abnormalCount = requiredDays - actualDays;
    const attendanceRate = requiredDays > 0 ? Math.round((actualDays / requiredDays) * 100) : 0;

    let status = "全勤";
    if (attendanceRate === 100) {
      status = "全勤";
    } else if (attendanceRate >= 90) {
      status = "缺卡";
    } else {
      status = "严重";
    }

    data.push({
      id: i + 1,
      name: name + (Math.floor(i / names.length) + 1),
      requiredDays,
      actualDays,
      morningShifts,
      afternoonShifts,
      abnormalCount,
      attendanceRate: attendanceRate + "%",
      status,
    });
  }

  return data;
};

// 所有数据
const allData = ref([]);

// 初始化数据
onMounted(() => {
  // 设置默认月份为当前月份
  const now = new Date();
  selectedMonth.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;

  // 生成模拟数据
  allData.value = generateMockData();
  loadTableData();
});

// 加载表格数据
const loadTableData = () => {
  loading.value = true;
  setTimeout(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    tableData.value = allData.value.slice(start, end);
    loading.value = false;
  }, 300);
};

// 月份变化
const handleMonthChange = (value) => {
  console.log("选择的月份：", value);
  // 这里可以重新加载数据
  currentPage.value = 1;
  loadTableData();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadTableData();
};

// 当前页变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadTableData();
};

// 获取状态样式类
const getStatusClass = (status) => {
  if (status === "全勤") {
    return "status-full";
  } else if (status === "缺卡") {
    return "status-missing";
  } else {
    return "status-serious";
  }
};

// 查看明细
const handleViewDetail = (row) => {
  // 格式化月份显示
  const monthText = selectedMonth.value
    ? `${selectedMonth.value.split('-')[0]}年${parseInt(selectedMonth.value.split('-')[1])}月`
    : new Date().toLocaleString('zh-CN', { year: 'numeric', month: 'long' });

  router.push({
    path: '/attendance/detail',
    query: {
      name: row.name,
      month: monthText,
    },
  });
};

// 导出功能
const handleExport = () => {
  try {
    // 准备导出数据
    const exportData = allData.value.map((item) => ({
      序号: item.id,
      成员姓名: item.name,
      应出勤天数: item.requiredDays,
      实际出勤天数: item.actualDays,
      上午班次: item.morningShifts,
      下午班次: item.afternoonShifts,
      异常缺勤次数: item.abnormalCount,
      出勤率: item.attendanceRate,
      状态: item.status,
    }));

    // 转换为CSV格式
    const headers = Object.keys(exportData[0]);
    const csvContent = [
      headers.join(","),
      ...exportData.map((row) =>
        headers.map((header) => `"${row[header]}"`).join(",")
      ),
    ].join("\n");

    // 添加BOM以支持中文
    const BOM = "\uFEFF";
    const blob = new Blob([BOM + csvContent], {
      type: "text/csv;charset=utf-8;",
    });

    // 创建下载链接
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", `考勤统计表_${selectedMonth.value || "全部"}.csv`);
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败：", error);
    ElMessage.error("导出失败，请重试");
  }
};
</script>

<style lang="scss" scoped>
.attendance-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  .header {
    height: 90px !important;
    min-height: 90px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #FFFFFF;
    box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.06);
    border-radius: 12px;
    padding: 0 26px 0 47px;

    .header-left {
      display: flex;
      align-items: center;

      .label {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 14px;
        color: #333333;
        margin-right: 10px;
      }
    }

    .header-right {
      .el-button {
        background: #2263bf;
        border-color: #2263bf;
      }
    }
  }

  .table-header {
    margin: 20px 0;

    .title-wrapper {
      display: flex;
      align-items: center;

      .title-icon {
        font-size: 18px;
        color: #2263bf;
        margin-right: 8px;
      }

      .title-text {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 16px;
        color: #333333;
      }
    }
  }

  .el-container {
    height: 100% !important;
    padding: 0 !important;
  }

  .el-main {
    padding: 0 !important;
  }

  .status-full {
    color: #67c23a;
    font-weight: 500;
  }

  .status-missing {
    color: #e6a23c;
    font-weight: 500;
  }

  .status-serious {
    color: #f56c6c;
    font-weight: 500;
  }
}
</style>
